package com.wu.common.utils.comment;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;

import android.text.Editable;

import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;


import com.alibaba.android.arouter.facade.annotation.Route;
import com.wkq.database.dao.UserInfo;
import com.wkq.database.utils.DataBaseUtils;
import com.wu.common.R;
import com.wu.common.utils.AlertUtil;
import com.wu.common.utils.NetworkUtil;

@Route(path = "/topic/TopicInputFragment")
public class TopicInputFragment extends Fragment implements View.OnClickListener, TextView.OnEditorActionListener {


    private final int INPUT_MAX = 100;
    private EditText chatEditText;

    private TextView chatSend;

    private View click_view, line;
    private String toSid;
    private String toName;
    private String currentPage;
    private LinearLayout anchorInputParentLayout;

    private ImageView emojiconsButton;

    private FrameLayout emojicons;

    private LinearLayout layout;

    private int displayScreenHeight;
    private int preHeightDifference;
    private int inputDefaultHeight;
    private int inputHeight;
    private boolean defaultShowEmoji = false;//首次弹窗是否显示emoji
    private boolean isFirstShowEmoji = true;//是否是首次显示emoji
    private boolean isLeader;//是否是领头雁
    private ImageView hideview;
    private boolean sendState = false;
    private String defValue="";

    private String news_type;
    private String news_Id;
    private String news_title;
    private String news_desc;
    private String news_icon;
    private boolean popError = false;
    private static boolean isClickEmoji = false;
    private RelativeLayout input_layout;
    private Handler inputHandler;
    private Runnable cancelInputAction;
    private int heightDifference = 0;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (getActivity() == null) return;
        if (chatEditText != null) {
            saveText(getActivity());
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) imm.hideSoftInputFromWindow(chatEditText.getWindowToken(), 0);
        }
        if (anchorInputParentLayout != null)
            anchorInputParentLayout.setVisibility(View.INVISIBLE);


    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getActivity() == null) return;
        if (getArguments() != null) {
            toSid = getArguments().getString("sid", "");
            toName = getArguments().getString("name", "");
            news_type = getArguments().getString("news_type", "");
            news_Id = getArguments().getString("news_Id", "");
            news_title = getArguments().getString("news_title", "");
            news_icon = getArguments().getString("news_icon", "");
            news_desc = getArguments().getString("news_desc", "");
            isLeader = getArguments().getBoolean("isLeader", false);
        }
        inputHandler = new Handler();
        cancelInputAction = new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null)
                    imm.hideSoftInputFromWindow(chatEditText.getWindowToken(), 0);
            }
        };
        WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();

    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_topic_input_view, container, false);
        input_layout = view.findViewById(R.id.input_layout);
        layout = view.findViewById(R.id.layout);
        chatEditText = view.findViewById(R.id.chatEditText);
        chatSend = view.findViewById(R.id.post_button);
        click_view = view.findViewById(R.id.click_view);
        line = view.findViewById(R.id.line);
        anchorInputParentLayout = view.findViewById(R.id.anchorInputParentLayout);
        emojiconsButton = view.findViewById(R.id.emoticons_button);
        emojicons = view.findViewById(R.id.emojicons);
        hideview = view.findViewById(R.id.hideView);
        String hintRes = getString(R.string.sp_topic_input_text);
        String hint = hintRes + String.format("(不超过%s字)", INPUT_MAX);

        if (!TextUtils.isEmpty(toName)) {
            String tempHint = "回复 " + toName + "  " + String.format("(不超过%s字)", INPUT_MAX);
            hint = tempHint;
        }
        chatEditText.setHint(hint);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getActivity() == null) return;
        inputHeight = (int) getActivity().getResources().getDimension(R.dimen.topic_input_default_height);
        inputDefaultHeight = (int) getActivity().getResources().getDimension(R.dimen.topic_input_height) + inputHeight;


        chatEditText.setText(defValue == null ? "" : defValue);
        if (sendState != defValue.length() > 0) {
            sendState = defValue.length() > 0;
            if (!isLeader) {
                chatSend.setBackgroundResource(sendState ? R.drawable.sp_btn_topic_send_sel : R.drawable.sp_btn_topic_send_nor);
            } else {
                chatSend.setBackgroundResource(sendState ? R.drawable.leader_btn_topic_send_sel : R.drawable.sp_btn_topic_send_nor);
            }
            chatSend.setTextColor(getResources().getColor(sendState ? R.color.white : R.color.topic_text_hint_color));
        }
        initDisplayScreen();
        screenAdapter();


        chatEditText.setOnEditorActionListener(this);
        chatEditText.requestFocus();
        chatEditText.setOnClickListener(this);
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) imm.showSoftInput(chatEditText, 0);
        click_view.setOnClickListener(this);
        anchorInputParentLayout.setOnClickListener(this);
        line.setOnClickListener(this);
        chatSend.setOnClickListener(this);
        hideview.setOnClickListener(this);
        emojiconsButton.setOnClickListener(this);
        chatEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (sendState != editable.length() > 0) {
                    sendState = editable.length() > 0;
                    if (!isLeader) {
                        chatSend.setBackgroundResource(sendState ? R.drawable.sp_btn_topic_send_sel : R.drawable.sp_btn_topic_send_nor);
                    } else {
                        chatSend.setBackgroundResource(sendState ? R.drawable.leader_btn_topic_send_sel : R.drawable.sp_btn_topic_send_nor);
                    }
                    chatSend.setTextColor(getResources().getColor(sendState ? R.color.white : R.color.topic_text_hint_color));
                }
            }
        });
    }

    private void initDisplayScreen() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Rect r = new Rect();
            layout.getWindowVisibleDisplayFrame(r);
            displayScreenHeight = r.bottom;
        }
    }

    private void screenAdapter() {
        anchorInputParentLayout.getLayoutParams().height = inputDefaultHeight;
        anchorInputParentLayout.setLayoutParams(anchorInputParentLayout.getLayoutParams());
        anchorInputParentLayout.setAlpha(0);
        layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (isContextDestroyed(getActivity())) return;
                Rect r = new Rect();
                //这里得到的是除了系统自带显示区域之外的所有区域，这里就是除了最上面的一条显示电量的状态栏之外的所有区域
                layout.getWindowVisibleDisplayFrame(r);
                int screenHeight = layout.getRootView().getHeight();
                heightDifference = 0;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    heightDifference = displayScreenHeight - r.bottom;
                } else {
                    heightDifference = screenHeight - (r.bottom);
                }

                if (heightDifference > 0 && (inputHeight != heightDifference + input_layout.getHeight())) {
                    inputHeight = heightDifference + input_layout.getHeight();
                    if (inputHeight < inputDefaultHeight) {
                        inputHeight = inputDefaultHeight;
                    }
                }

                //默认显示emoji
                if (preHeightDifference != heightDifference) {
                    if (heightDifference > 100) {
                        anchorInputParentLayout.getLayoutParams().height = inputHeight;
                        anchorInputParentLayout.setLayoutParams(anchorInputParentLayout.getLayoutParams());
                        anchorInputParentLayout.setAlpha(1);
                        if (defaultShowEmoji && isFirstShowEmoji) {
                            changeEmojiconsVisible(true);
                            isFirstShowEmoji = false;
                            if (null != inputHandler && null != cancelInputAction) {
                                inputHandler.removeCallbacksAndMessages(null);
                                inputHandler.postDelayed(cancelInputAction, 300);
                            }
                        }
                    } else {
                        if (getActivity() == null) return;
                        if (emojicons.getVisibility() != View.VISIBLE && null != emojicons.getTag() &&
                                !isClickEmoji) {
                            destroyInputFragment();
                            try {
                                popError = false;
                            } catch (Exception e) {
                                popError = true;
                                destroyInputFragment();
                                getActivity().getSupportFragmentManager().popBackStack(null, 0);
                            }
                        }
                    }
                    preHeightDifference = heightDifference;
                }

            }
        });

    }

    public boolean isContextDestroyed(Context context) {
        if (context == null) return true;
        return context instanceof Activity && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && ((Activity) context).isDestroyed();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEND) sendClick();
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.post_button) {
            sendClick();
        } else if (v.getId() == R.id.click_view) {
            layout.setVisibility(View.GONE);
            closeInputPage();
            destroyInputFragment();
        } else if (v.getId() == R.id.emoticons_button) {
            onClickBtn();
        } else if (v.getId() == R.id.chatEditText || v.getId() == R.id.line) {
            onEditClick();
        } else if (v.getId() == R.id.hideView) {
            layout.setVisibility(View.GONE);
            destroyInputFragment();
        }
    }

    private void sendClick() {
        String msg = chatEditText.getText().toString().trim();
        if (msg.length() <= INPUT_MAX && msg.length() > 0) {
            if (NetworkUtil.isConnectInternet(getActivity())) {
                sendContent(msg.replace("\n", "\t"));
                chatEditText.setText("");
            } else {
                AlertUtil.showDeftToast(getActivity(), "无法连接网络");
            }
            if (anchorInputParentLayout != null)
                anchorInputParentLayout.setAlpha(0);
            closeInputPage();
            destroyInputFragment();
        } else if (msg.length() > INPUT_MAX) {
            AlertUtil.showDeftToast(getActivity(), "评论内容不能超过" + INPUT_MAX + "字.");
        } else {
            AlertUtil.showDeftToast(getActivity(), "请输入评论内容");
        }
    }

    private void sendContent(String replace) {
        UserInfo info = DataBaseUtils.getUser(getActivity());
        DataBaseUtils.insertNewsComment(getActivity(), replace, news_type, news_Id, info.getUserIcon(), info.getUserName(),news_title,news_desc,news_icon);
    }

    private void saveText(FragmentActivity activity) {
        if (chatEditText == null || activity == null) return;

        Editable message = chatEditText.getText();
        String text = message == null ? "" : message.toString().trim();
//        hideInput(text);
    }


    protected void destroyInputFragment() {
        if (null != inputHandler && null != cancelInputAction) {
            inputHandler.removeCallbacksAndMessages(null);
        }
        if (getActivity() == null) return;
        isClickEmoji = false;
        emojicons.setTag("noClick");
        layout.setVisibility(View.GONE);
        if (chatEditText.getWindowToken() == null) return;
        saveText(getActivity());
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) imm.hideSoftInputFromWindow(chatEditText.getWindowToken(), 0);
        if (null != getActivity().getSupportFragmentManager().beginTransaction()) {
            getActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .remove(this)
                    .commitAllowingStateLoss();
        }
    }

    protected void onClickBtn() {
//        if (getActivity() == null) return;
//        if (emojicons.getVisibility() == View.VISIBLE) {
//            changeEmojiconsVisible(false);
//            if (0 == inputHeight) {
//                anchorInputParentLayout.getLayoutParams().height = inputDefaultHeight;
//            } else {
//                anchorInputParentLayout.getLayoutParams().height = inputHeight;
//            }
//            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
//            if (imm != null) imm.showSoftInput(chatEditText, 0);
//        } else {
//            changeEmojiconsVisible(true);
//            if (0 == inputHeight) {
//                anchorInputParentLayout.getLayoutParams().height = inputDefaultHeight;
//            } else {
//                anchorInputParentLayout.getLayoutParams().height = inputHeight;
//            }
//            saveText(getActivity());
//            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
//            if (imm != null) imm.hideSoftInputFromWindow(chatEditText.getWindowToken(), 0);
//        }
    }

    private void onEditClick() {
        if (getActivity() == null) return;
        if (emojicons.getVisibility() == View.VISIBLE) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) imm.showSoftInput(chatEditText, 0);
            changeEmojiconsVisible(false);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() == null) return;
        if (chatEditText != null) {
            saveText(getActivity());
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) imm.hideSoftInputFromWindow(chatEditText.getWindowToken(), 0);
//            changeEmojiconsVisible(false);
            anchorInputParentLayout.getLayoutParams().height = inputHeight;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if (isClickEmoji) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) imm.hideSoftInputFromWindow(chatEditText.getWindowToken(), 0);
        }
        if (popError) {
            getActivity().getSupportFragmentManager().popBackStack(null, 0);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public void closeInputPage() {
        if (getActivity() == null) return;
        isClickEmoji = false;
        anchorInputParentLayout.getLayoutParams().height = 0;
        anchorInputParentLayout.setLayoutParams(anchorInputParentLayout.getLayoutParams());
        if (null != inputHandler && null != cancelInputAction) {
            inputHandler.removeCallbacksAndMessages(null);
        }
        if (chatEditText != null) {
            saveText(getActivity());
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) imm.hideSoftInputFromWindow(chatEditText.getWindowToken(), 0);
        }
        if (emojicons.getVisibility() == View.VISIBLE || anchorInputParentLayout.getHeight() == inputHeight) {
            if (getActivity() == null) return;
            getActivity().getSupportFragmentManager().popBackStackImmediate();
            anchorInputParentLayout.setAlpha(0);
        }

    }

    private void changeEmojiconsVisible(boolean isShow) {
        isClickEmoji = isShow;
        emojicons.setVisibility(isShow ? View.VISIBLE : View.GONE);
        emojiconsButton.setImageResource(
                isShow ? R.drawable.sp_btn_topic_keyboard_sel : R.drawable.sp_btn_topic_emoj);
        if (isShow) {
            emojicons.setTag("click");
        } else {
            emojicons.setTag("noClick");
        }
    }

}